<template>
	<view class="pageStyle">
		<view :class="[{'bodyStyle':true}, {'bodyStyleGrid':isGrid}]">
			<view class="content_box" v-if="!isGrid">
				<view class="content_box_item" v-for="(typeItem, index) in list" :key="index">
					<uni-section titleFontSize="36rpx" class="app-section" :title="typeItem.appTypeName" color="#191919"
						:arrow="false">
						<template v-slot:right>
							<uni-icons :type="typeItem.arrow" color="#bbb" size="18"
								@click="handleClickArrow(typeItem)"></uni-icons>
						</template>
					</uni-section>
					<view v-if="typeItem.arrow == 'down'">
						<view class="app_box_center flex">
							<view class="app_box_center_text" v-for="(item,idx) in typeItem.children" in :key="idx"
								:style="[{height: 'calc(94.5% / 4)'}]"
								@click="todoItem(item,index)">
								<uni-badge :text="nums.noticeNum" size="normal" bgColor="#f00" :showZero="false"
									class="badge my-badge app-badge"
									v-if="item.code&&item.code.indexOf('notice/listPage')!=-1 || (item.formCode && item.formCode.indexOf('notice')==0)"></uni-badge>
								<uni-badge :text="nums.waitNum" bgColor="#f00" :showZero="false"
									class="badge my-badge app-badge" v-if="item.code=='flow_wait'"></uni-badge>
								<uni-badge :text="nums.messageNum" bgColor="#f00" :showZero="false"
									class="badge my-badge app-badge"
									v-if="item.code&&item.code.indexOf('listNewMsgPage')!=-1"></uni-badge>
								<uni-badge :text="nums.internalEmailNum" bgColor="#f00" :showZero="false"
									class="badge my-badge app-badge"
									v-if="item.code&&item.code.indexOf('internalEmail')!=-1 || (item.link && item.link.indexOf('internalEmail')!=-1)"></uni-badge>
								<view class="app_block">
									<view class="app_img">
										<image :src="item.imgUrls" class="img" :style="[{backgroundColor: item.backgroundColor}]"></image>
									</view>
									<view class="app_title">
										{{item.mName}}
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="content_box" v-else>
				<view class="content_box_center flex">
					<view class="content_box_center_text" v-for="(item,index) in list" in :key="index"
						:style="[{marginRight:(index+1)%4==0?'0':'1.5%',marginBottom:'1.5%',height: 'calc(94.5% / 4)'}]"
						@click="todoItem(item,index)">
						<uni-badge :text="nums.noticeNum" size="normal" bgColor="#f00" :showZero="false"
							class="badge my-badge"
							v-if="item.code&&item.code.indexOf('notice/listPage')!=-1 || item.formCode&& item.formCode.indexOf('notice')==0"></uni-badge>
						<uni-badge :text="nums.waitNum" bgColor="#f00" :showZero="false" class="badge my-badge"
							v-if="item.code&&item.code=='flow_wait'"></uni-badge>
						<uni-badge :text="nums.messageNum" bgColor="#f00" :showZero="false" class="badge my-badge"
							v-if="item.code&&item.code.indexOf('listNewMsgPage')!=-1"></uni-badge>
						<uni-badge :text="nums.internalEmailNum" bgColor="#f00" :showZero="false" class="badge my-badge"
							v-if="item.code&&item.code.indexOf('internalEmail')!=-1 || (item.link && item.link.indexOf('internalEmail')!=-1)"></uni-badge>
						<view class="con_block">
							<view class="con_img">
								<image :src="item.imgUrls" class="img"></image>
							</view>
							<view class="con_title">
								{{item.mName}}
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>
<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		postAction,
		getAction
	} from "@/utils/request";
	import {
		Api
	} from "@/utils/Api.js";
	import {
		setUserInfo,
		Toast,
		getSkey
	} from "@/utils/commonHeader.js";
	import {
		mapState
	} from "vuex";
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app'

	const customStyle = ref({
		margin: "0rpx",
	})
	const url = {
		list: "/mobile/getAppIcons",
	}
	const isGrid = ref(true)
	const list = ref([])
	const nums = ref({
		noticeNum: 0, //告知单数量
		waitNum: 0, //待办流程数量
		messageNum: 0, //消息数量
		internalEmailNum: 0 // 内部邮件数量
	})

	// onLoad(() => {
	// 	getUserInfo();
	// 	console.log("ApplicationView-onLoad")
	// })
	// onShow(() => {
	// 	console.log("ApplicationView-onShow")
	// 	getList();
	// 	getNoticeNum();
	// })
	onMounted(() => {
		console.log("ApplicationView-onMounted")
		getUserInfo();
		getList();
		getNoticeNum();
	})

	function handleClickArrow(typeItem) {
		if (typeItem.arrow == 'down') {
			typeItem.arrow = 'up';
		} else {
			typeItem.arrow = 'down';
		}
		// 重新赋值，插槽中的图标才会跟着有变化或者用$forceUpdate
		// list.value = [...list.value]
		// this.$forceUpdate();
	}

	function getList() {
		getAction(url.list).then((res) => {
			if (res.res == 0) {
				isGrid.value = res.result.isGrid;
				list.value = res.result.datas;
				if (list.value && list.value.length > 0) {
					if (isGrid.value) {
						list.value.map((item) => {
							item.imgUrls = item.imgUrl ? Api.baseUrl + "/" + item.imgUrl : "";
							// if (item.code == "usercardrecord") {
							//   getNoticeNum(item.mId);
							// }
						});
					} else {
						list.value.map((item) => {
							item.arrow = 'down';
							item.children.map((it) => {
								it.imgUrls = it.imgUrl ? Api.baseUrl + "/" + it.imgUrl :
									"";
							});
						});
					}
				} else {
					list.value = [];
				}
			}
		});
	}
	//获得消息数
	async function getNoticeNum(mId) {
		let res = await postAction("/public/android/getBadgeNum", {}, 'post', {
			skey: getSkey(),
			'content-type': 'application/x-www-form-urlencoded'
		});
		if (res.res == 0) {
			console.log("res", res);
			nums.value = Object.assign(nums.value, res);
			console.log("nums", nums.value);
		}
	}

	function todoItem(item, index) {
		console.log("todoItem", item)
		let mId = item.mId;
		let code = item.code;
		let pageUrl = "";
		if (code == 'flow_wait' || code == 'doing') {
			// 待办流程
			// pageUrl = "/application/waitProcessListH5";
			pageUrl = "/sub_flow/doingFlow/DoingFlow";
		} else if (code == 'myflow' || code == 'attend') {
			// 我的流程
			// pageUrl = "/application/hadProcessListH5";
			pageUrl = "/sub_flow/mineFlow/MineFlow";
		} else if (code == 'distFlow') {
			// 抄送流程
			pageUrl = "/sub_flow/distFlow/DistFlow";
		}
		else if (code == 'flow_launch' || code == 'launch') {
			// 发起流程
			// pageUrl = "/application/initProcessListH5";
			pageUrl = "/sub_flow/startFlow/StartFlow";
		} else if (code == 'internalEmail' || code == '1720775697699') {
			//内部邮箱
			pageUrl = "/cmn/internalEmail/index";
		} else if (code == 'externalEmail' || code == '1723432346511') {
			//外部邮箱
			pageUrl = "/cmn/externalEmail/index";
		} else if (code == 'schedule') {
			// 日程安排
			pageUrl = "/cmn/schedule/Schedule";
		} else if (code == 'punch') {
			// 打卡
			pageUrl = "/cmn/clockIn/ClockIn" //"/application/punch";
		} else if (code == 'message') {
			// 系统消息
			pageUrl = "/application/sysMessage";
		}
		/* else if (code == 'fileark') {
							pageUrl = "/application/filearkDir";
						}*/
		else if (code == 'fileark') {
			pageUrl = "/application/moduleTreeList";
		} else if (code == 'notice') {
			pageUrl = "/application/noticeList";
		} else if (code == 'address') {
			pageUrl = "/application/address";
		} else if (mId == 16) {
			// 系统消息
			pageUrl = "/application/sysMessage";
		} else if (mId == 21) {
			pageUrl = "/application/noticeList";
		} else if (mId == 13) {
			// pageUrl = "/application/calendar";
			pageUrl = "/cmn/schedule/Schedule";
		} else if (mId == 14) {
			pageUrl = "/application/calendarShared";
		} else if (mId == 18) {
			pageUrl = "/cmn/clockIn/ClockIn" //"/application/punch";
		} else if (code == 'addressAll') {
			item.isAll = true;
			pageUrl = "/application/addressBook/AddressBook";
		} else if (mId == 23) {
			//通讯录
			// pageUrl = "/application/address";
			// item.isAll = true;
			pageUrl = "/application/addressBook/AddressBook";
		}
		/* else if (mId == 34) {
			//内部邮箱
			pageUrl = "/cmn/internalEmail/index";
		} else if (mId == 35) {
			//外部邮箱
			pageUrl = "/cmn/externalEmail/index";
		} */
		else {
			if (item.type === 3) {
				pageUrl = "/application/moduleList";
			} else if (item.type == 2) {
				pageUrl = "/application/processInit";
			} else {
				console.log('item', item);
				if (item.code != 'scan') {
					uni.showToast({
						title: "开发中",
						icon: "none",
						duration: 1000,
					});
				}
			}
		}

		if (item.code == 'scan') {
			scanQrcode();
		} else {
			uni.navigateTo({
				url: `${pageUrl}?record=${JSON.stringify(item)}`,
			});
		}
	}

	function scanQrcode() {
		let r = false;
		uni.scanCode({
			success: (res) => {
				console.log("scan1 res", res);
				r = doScan(res);
				if (!r) {
					Toast('none', '扫码失败，尝试第2次');
					uni.scanCode({
						success: (res) => {
							console.log("scan2 res", res);
							r = doScan(res);
							if (!r) {
								Toast('none', '扫码失败，尝试第3次');
								uni.scanCode({
									success: (res) => {
										console.log("scan3 res", res);
										r = doScan(res);
										if (!r) {
											Toast('none', '扫码失败，请重新扫码');
										}
									},
								});
							}
						},
					});
				}
			},
		});
	}

	async function doScan(res) {
		let resultRaw = res.result;
		console.log('resultRaw', resultRaw);
		let result = null;
		try {
			result = JSON.parse(resultRaw);
		} catch (e) {
			console.log(e);
		}
		console.log('result', result);
		if (result == null) {
			console.log('扫码结果: ' + resultRaw);
			let resBar = await postAction("/public/android/getBarcode", {
				barcode: resultRaw
			}, 'post', {
				skey: getSkey(),
				'content-type': 'application/x-www-form-urlencoded'
			});
			console.log('resBar', resBar);
			if (resBar.code == 200) {
				result = resBar.data;
			} else {
				Toast('none', resBar.msg);
				return false;
			}
		}
		console.log("scanCode-result", result);
		if (result.scanActionType) {
			if (result.scanActionType == 'flow') {
				result.scanId = result.id;
				let pageUrl = '/application/process';
				uni.navigateTo({
					url: `${pageUrl}?record=${JSON.stringify(result)}`,
				});
				return true;
			} else if (result.scanActionType == 'create') {
				result.scanId = result.id;
				delete result['id'];
				console.log('create result', result);
				let pageUrl = '/application/moduleAddEdit';
				uni.navigateTo({
					url: `${pageUrl}?record=${JSON.stringify(result)}`,
				});
				return true;
			}
		}

		// 如果存在url
		if (result.url) {
			let pageUrl = result.url;
			uni.navigateTo({
				url: `${pageUrl}?record=${JSON.stringify(result)}`,
			});
		} else {
			if (!result.id) {
				console.log('扫码识别失败: ' + res.result);
				return false;
			} else {
				let pageUrl = '/application/moduleShow';
				uni.navigateTo({
					url: `${pageUrl}?record=${JSON.stringify(result)}`,
				});
			}
		}
		return true;
	}

	function getUserInfo() {
		postAction("/public/android/i/info").then((res) => {
			if (res.res == 0) {
				let uesrInfo = res.result;
				uni.setStorage({
					key: "uesrInfo",
					data: uesrInfo,
					success() {
						//存储个人信息
						setUserInfo();
					},
				});
			}
		});
	}
</script>
<style lang='scss' scoped>
	.pageStyle {
		height: 100%;

		image {
			will-change: transform;
		}

		.bodyStyleGrid {
			height: 100%;
			background-color: #f4f4f4;
		}

		.bodyStyle {
			.content_box {
				position: relative;
				width: 100%;
				display: flex;
				flex-direction: column;
				gap: 30rpx;

				&_item {
					border-radius: 16rpx;
					background-color: #fff;
					padding: 30rpx;
				}
			}

			.content_box_center {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				/* 铺满父元素容器，这时候宽高就始终相等了 */
			}

			.content_box_center>.content_box_center_text {
				width: calc(94.5% / 4);
				/* calc里面的运算符两边要空格 */
				box-shadow: #1c6ec4 0px 0px 20rpx;
				border-radius: 10rpx;
				position: relative;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.con_block {
				.con_img {
					position: relative;
					width: 100%;
					height: 42rpx;
					margin-bottom: 20rpx;

					.img {
						position: absolute;
						top: 10rpx;
						left: 50%;
						transform: translateX(-50%);
						width: 64rpx;
						height: 64rpx;
					}
				}

				.con_title {
					font-size: 29rpx;
					padding-top: 28rpx;
				}
			}

			.flex {
				display: flex;
				flex-wrap: wrap;
				align-content: flex-start;
			}

			.flex>.content_box_center_text {
				//   flex-grow: 1; /* 子元素按1/n的比例进行拉伸 */
				background-color: #ffffff;
				text-align: center;
				color: #999;
				font-size: 50px;
				// line-height: 1.5;
			}

			.app_box_center>.app_box_center_text {
				width: 25%;
				/* calc里面的运算符两边要空格 */
				border-radius: 10rpx;
				position: relative;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.app_block {
				margin-top: 20rpx;

				.app_img {
					position: relative;
					width: 100%;
					height: 90rpx;
					margin-bottom: 20rpx;

					.img {
						position: absolute;
						top: 10rpx;
						left: 50%;
						transform: translateX(-50%);
						width: 60rpx;
						height: 60rpx;
						padding: 20rpx;
						border-radius: 16px;
					}
				}

				.app_title {
					font-size: 29rpx;
					padding-bottom: 20rpx;
					padding-top:20rpx;
				}
			}

			.badge {
				z-index: 1000;
			}
		}
	}

	.my-badge {
		font-size: 24rpx;
		z-index: 900 !important;
	}

	.app-badge {
		position: absolute;
		right: 0;
		top: 5rpx;
	}

	.app-section {
		margin: 0;
		background-color: #fff;

		::v-deep .line {
			background-color: #1c6ec4;
		}

		::v-deep .uni-section__content-title {
			color: #393939;
			font-weight: bold;
			font-size: 32rpx;
		}
	}

	::v-deep .uni-section-header {
		padding: 0 0 30rpx !important;
	}
</style>